package com.shu.rpc.rpc1.client;

import com.shu.rpc.rpc1.common.service.ProductService;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @author ssm
 * @version V1.0
 * @description:
 * @date 2020/6/12 10:09
 */

public class Stubs {

    /**
     * 客户端获取代理对象
     *
     * @param clz
     * @return
     */
    public static Object getStub(Class clz) {

        // 动态代理
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // socket 连接服务端,传输参数(类+方法+参数),获取返回值
                Socket socket = new Socket("127.0.0.1",8888);

                OutputStream os = socket.getOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(os);

                // 传输参数(类+方法+参数)
                String methodName = method.getName();
                Class<?>[] parameterTypes = method.getParameterTypes();
                oos.writeUTF(clz.getName());
                oos.writeUTF(methodName);
                oos.writeObject(parameterTypes);
                oos.writeObject(args);
                oos.flush();

                // 从socket中 获取返回值
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                Object readObject = ois.readObject();

                return readObject;
            }
        };

        Object proxyInstance = Proxy.newProxyInstance(
                ProductService.class.getClassLoader(),
                new Class[]{ProductService.class},
                h);

        return proxyInstance;
    }
}
